<?php
use Entities\Cadastrado;

include_once '../templates/topo.php';

$id= '';

$functionRetornar = isset($_REQUEST['functionRetornar'])?$_REQUEST['functionRetornar']: "click";



if(isset($_REQUEST['id']))
	$id = $_REQUEST['id'];
	
$recibo = $em->find("Entities\Recibo", $id);
if(empty($recibo)){
	$recibo = new Entities\Recibo();
	echo "<script>var iniciaDisabled = true</script>";
}
else{
	echo "<script>
			var iniciaDisabled = false;
			$(document).ready(function(){
								carregarReferencias();
								$('#btnExcluir').button('option', 'disabled', false);
								$('#AdicionarReferencia').button('option', 'disabled', false);
							})
			</script>";
}
	
	
?>

	<div class="tabs center">
			<ul>
				<li><a href="#tabs-1">Recibo</a></li>
			</ul>
			<div id="tabs-1">
				<div cols='3' style='display:table; width:100%'>
					<div class='field' >
						<label>Numero Recibo</label>
						<input type='text' id='txtId' value='<?php echo $recibo->getId();?>' readonly="readonly" size='30' onkeypress="mascara(this,maiusculo)" />
						
					</div>
					<div class='field'>
						<label>Pessoa</label>
						<input type='text' id='txtNomeCadastrado' readonly="readonly" value='<?php echo $recibo->getCadastrado()->getNome();?>' size='20' />
						<input type='hidden' id='hidIdCadastrado'  value='<?php echo $recibo->getCadastrado()->getId();?>' />
						<button id="btnSelecionaCadastrado">Selecionar Pessoa Cadastrada</button>
						<script>
							$("#btnSelecionaCadastrado").click(function(e){
								e.stopImmediatePropagation();
								utils.abrirJanela("cadastrado/FormConsultaCadastrado.php", "popup=true", "retornoConsultaCadastrado");
								
							});
							$("body").bind("retornoConsultaCadastrado", function(e, data){

								utils.ajax("recibo/adcionarCadastrado",{
									idRecibo: $("#txtId").val(),
									idCadastrado: data.id
									}, function(xml){

										var json = $.xml2json(xml);
										if(json.error == "0"){
											
											$("#hidIdCadastrado").val(data.id);
											$("#txtNomeCadastrado").val(data.nome);
											teste();
											utils.fecharJanela();
											
										}
								});
							});
						</script>
					</div>
					<div class='field'>
							<label>Terreno</label>
							<select id="selTerreno">
								
								<?php if(empty($id)){?>
									<option value="0">Selecione</option>
								<?php }else{
									$idAtual = $recibo->getPropriedade()->getId();
									$propriedades = $recibo->getCadastrado()->getPropriedades();
									
									foreach ($propriedades as $p){
										$selected = ($idAtual == $p->getId())? "selected='selected'": '';
										?>
										
										<option value="<?php echo $p->getId();?>" <?php echo $selected;?> ><?php echo "{$p->getRua()}, {$p->getNumero()} - {$p->getBairro()}"; ?></option>
										<?php 
										
									}
									
									
									?>
									
									
									
								<?php }?>
								
								
							</select>
								<script type="text/javascript">
									function teste(){
										utils.ajax("recibo/adcionarTerreno",{
												idMorador: $("#hidIdCadastrado").val()
											}, function(xml){
													var option="";
													$(xml).find('terreno').each(function(){
														var id= $(this).find('id').text();
														var bairro= $(this).find('bairro').text();
														var rua= $(this).find('rua').text();
														var numero= $(this).find('nro').text();
														
														option += "<option value='"+id+"'>"+bairro+" - "+rua+", "+numero+"</option>";
													});

													$('#selTerreno').html(option);
													$('#selTerreno').selectmenu();
												});
									};
								</script>	
					</div>
					
					
				</div>
				<div cols='6'>	
<!--					<div class='field'>-->
<!--						<label>Data Pagamento</label>-->
<!--						<input type='text' id='txtDataPagamento' readonly="readonly" value='<?php $d=$recibo->getDataPagamento(); echo empty($d)? "": date("d/m/Y", $recibo->getDataPagamento()->getTimestamp());?>' size='12' />-->
<!--						<script type="text/javascript">-->
<!--							$("#txtDataPagamento").setMask('date');-->
<!--						</script>-->
<!--					</div>-->
					<div class='field'>
						<label>&nbsp;</label>
						<select id="selTaxas">
							<option value="0">Selecione</option>
							<option value="Taxa de agua, portaria e manutencao.">Taxa de agua, portaria e manutencao.</option>
							<option value="Taxa portaria e manutencao.">Taxa de portaria e manutencao.</option>
						</select>
						<script type="text/javascript">
							$(document).ready(function(){
								$("#selTaxas").change(function(){
									if($("#selTaxas").val() == 'Taxa de agua, portaria e manutencao.'){
										$("#txtObservacao").val('Taxa de agua, portaria e manutencao.');
										$("#txtValorRef").val('70.00');
										}
									else if($("#selTaxas").val() == 'Taxa portaria e manutencao.'){
										$("#txtObservacao").val('Taxa portaria e manutencao.');
										$("#txtValorRef").val('35.00');
									}
									else if($("#selTaxas").val() == 0){
										$("#txtObservacao").val('');
										$("#txtValorRef").val('');
									}
								});
							});
						</script>
					</div>
					<div class='field'>
						<label>Descricao</label>
						<input type="text" id='txtObservacao' size="30"  />
					</div>
					<div class='field'>
						<label>Ref Inicial:</label>

						<input type="text" id="refInicial" class='monthPicker' />
						
					</div>
					
					<div class='field'>
						<label>Ref Final</label>
						<input type="text" id="refFinal" class='monthPicker' />
					</div>
					<script>
//							$(".monthPicker").datepicker();
							$(".monthPicker").datepicker({
								dateFormat: 'MM yy',
								changeMonth: true,
								changeYear: true,
								showButtonPanel: true,
								showAnim: "",
								
								onClose: function(dateText, inst) {
									var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
									var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
									$(this).val($.datepicker.formatDate('mm/yy', new Date(year, month, 1)));
								}
								
								
							});
							
							
							
							
							$(".monthPicker").focus(function () {
//								$( ".monthPicker" ).datepicker( "dialog", "10/12/2012");
//								$("#ui-datepicker-div").css('z-index', '9');
								$(".ui-datepicker-calendar").hide();
								$("#ui-datepicker-div").position({
									my: "top",
									at: "bottom",
									of: $(this)
								});
							});
						
						</script>

					
					<div class='field'>
						<label>&nbsp;</label>
						<button id="AdicionarReferencia">Adicionar Referencia</button>
						<button id="RemoverReferencia">Remover Referencia</button>
						
						<script type="text/javascript">

							function calculaTotalItemRef(){
								var valorItem = !(isNaN(parseFloat($("#txtValorRef").val())))? parseFloat($("#txtValorRef").val()) : 0; 
								var acrescimoItem =!(isNaN(parseFloat($("#txtAcrescimoRef").val())))? parseFloat($("#txtAcrescimoRef").val()) : 0;

								var valorTotal = acrescimoItem + valorItem;
								valorTotal =!(isNaN(parseFloat(valorTotal)))? parseFloat(valorTotal).toFixed(2) : "0.00";
								$("#txtTotalRef").val(valorTotal);
								 
							}
						
							$("#btnSelecionaCadastrado").button({
								text: false,
								disabled: iniciaDisabled,
								icons: {
									primary: "ui-icon-search"
								}
							});

							$("#RemoverReferencia").button({
								text: false,
								disabled: false,
								icons: {
									primary: "ui-icon-trash"
								}
							});
							
							$("#AdicionarReferencia").button({
								text: false,
								disabled: iniciaDisabled,
								icons: {
									primary: "ui-icon-plusthick"
								}
							});

							$("#RemoverReferencia").click(function(){

								showAlertPopup({
									title: "Remover",
									msg: "Tem certeza que deseja excluir essa referencia",
									buttons: {
										"Sim": function(){
									
											utils.ajax("recibo/removeReferencia",{
												idReferencia: $('[name="radRef"]:checked').val()
												
											}, function(xml){
												carregarReferencias();
												closeAlertPopup();
											});
											
										},
										"Nao": closeAlertPopup
									}
								});
								
							});
							
							$("#AdicionarReferencia").click(function(){

								if($("#txtObservacao").val() == "" || $("#refInicial").val() == '' || $("#refFinal").val() =='' ){
									alert("Atencao!<br />Todos os dados de referencia sao obrigatorios. Verifique se todos estao preenchidos corretamente!");
								}
								else{
								
							

								
									
									utils.ajax("recibo/adcionarReferencia", {
											idRecibo: $("#txtId").val(),
											descricao: $("#txtObservacao").val(),
											refInicial: $("#refInicial").val(),
											refFinal: $("#refFinal").val()
											
											
										}, function(xml){
											var json = $.xml2json(xml);
		
											var erro = json.error;
		
											if(erro == "0"){
												carregarReferencias();
												$("#txtObservacao").val("");
												$("#refInicial").val("");
												$("#refFinal").val("");
												$("#txtObservacao").focus();
											}
										
	
										
									});
								}
								
							});

							function carregarReferencias(){
								utils.ajax("recibo/getReferencias",{
									idRecibo: $("#txtId").val()
									
								}, function(xml){
									var json = $.xml2json(xml);
									utils.limparTabela(".table_consulta")
									$(json.referencia).each(function(c){
										var chkbox = "<input type='radio' name='radRef' value='"+this.id+"' />";
										var linha = utils.gerarLinha([
																		this.id,
																		chkbox,
																		this.obs,
																		this.referenciaInicial,
																		this.referenciaFinal
																		
																		
																		], 0,"ref", c, false);

										

										$(".table_consulta").append(linha);
										
										$('#ref_'+ this.id).click(function(e){
											if($('[name="radRef"]', $(this)).is(":checked")){
												$('[name="radRef"]', $(this)).attr("checked", "");
											}
											else{
												$('[name="radRef"]', $(this)).attr("checked", "checked");
											} 
										});
									});

									calcularTotais();
									
								});
							}
						</script>
						
						
					</div>
					
					<div cols="1">
						<table class="table_consulta">
						
							<tr>
								<th>&nbsp;</th>
								<th>Descricao</th>
								<th>Ref Inicial</th>
								<th>Ref Final</th>
							</tr>
							
							
							<tfoot>
								<tr>
									<td colspan="7">Nenhuma Referencia</td>
								</tr>
							</tfoot>
						</table>
					</div>
				</div>
				<div cols="6">
					<div class='field'>
						<label>Valor</label>
						<input type="text" id="txtValorRef" size="10" onkeypress="mascara(this, tiraVirgula)" onblur="calculaTotalItemRef()" value="<?php echo number_format($recibo->getValor(), 2, '.', '');?>" class='dinheiro' />
					</div>
					<div class='field'>
						<label>Acrescimo</label>
						<input type="text" id="txtAcrescimoRef" size="10" onkeypress="mascara(this, tiraVirgula)"  onblur="calculaTotalItemRef()" value="<?php echo number_format($recibo->getAcrescimo(), 2, '.', '');?>" class='dinheiro' />
					</div>
						<div class='field'>
						<label>Em dinheiro</label>
						<input type="text" id="txtDinheiroRef" size="10" onkeypress="mascara(this, tiraVirgula)" value="<?php echo number_format($recibo->getDinheiro(), 2, '.', '');?>" class='dinheiro'   />
					</div>
					<div class='field'>
						<label>No cart&atilde;o</label>
						<input type="text" id="txtCartaoRef" size="10" onkeypress="mascara(this, tiraVirgula)"  value="<?php echo number_format($recibo->getCartao(), 2, '.', '');?>" class='dinheiro'  />
					</div>
					<div class='field'>
						<label>No cheque</label>
						<input type="text" id="txtChequeRef" size="10" onkeypress="mascara(this, tiraVirgula)"  value="<?php echo number_format($recibo->getCheque(), 2, '.', '');?>" class='dinheiro'  />
					</div>
					<div class='field'>
						<label>Total</label>
						<input type="text" id="txtTotalRef" readonly="readonly" size="10" onkeypress="mascara(this, tiraVirgula)" value="<?php echo number_format($recibo->getTotal(), 2, '.', '');?>" class='dinheiro'  />
					</div>
					
					<script>
						$(document).ready(function(){
							$('.dinheiro').setMask('dinheiro');
						});
						
					</script>
				</div>
			</div>
	
			<div class='footer'>
			
<!--				<div id="divTotais" style="float: left; padding: 0.2em;">-->
<!--					<label style="float: left; padding: 0.5em;">Total Contas: R$ </label>-->
<!--					<div id="divTotalContas" style="float: left;padding: 0.5em;">0.00</div>-->
<!--					-->
<!--					<label style="float: left; padding: 0.5em;">Total Adicional: R$ </label>-->
<!--					<div id="divTotalAdicional" style="float: left; padding: 0.5em;">0.00</div>-->
<!--					-->
<!--					<label style="float: left; padding: 0.5em;">Total: R$ </label>-->
<!--					<div id="divTotalGeral" style="float: left; padding: 0.5em;">0.00</div>-->
<!--				</div>-->
				
				<button id='btnExcluir'>Excluir</button>
				<button id='btnIniciar'>Iniciar</button>
				<button id='btnFechar'>Salvar / Fechar</button>
				<script type="text/javascript">
					function atualizaTotais(){
						utils.ajax("recibo/atualizaTotalGeral", {
							totalGeral: $("#divTotalGeral").text(),
							idRecibo: $("#txtId").val()
						}, function(xml){});
					}
					
					function calcularTotais(){
						
						trs = $(".table_consulta tr");
						var totalValorItem = 0;
						var totalValorAd = 0;
						var totalValor = 0;
//						var cont = 0;
						$(trs).each(function(c){
							
//							cont++;
							if(c!=0){
								tds = $("td", $(this));
								var valorItem = isNaN(parseFloat($(tds[4]).text()))? 0.00: parseFloat($(tds[4]).text());
								var valorAd =  isNaN(parseFloat($(tds[5]).text()))?0.00: parseFloat($(tds[5]).text());
								var total = isNaN(parseFloat($(tds[6]).text()))? 0.00: parseFloat($(tds[6]).text());


								totalValorItem+=valorItem;
								totalValorAd+=valorAd;
								totalValor+=total;

							}
							
						});

//						alert(totalValorItem)
						$("#divTotalContas").text(totalValorItem.toFixed(2));
						$("#divTotalAdicional").text(totalValorAd.toFixed(2));
						$("#divTotalGeral").text(totalValor.toFixed(2));
						atualizaTotais();
						
					}
					$("#btnExcluir").click(function(e){
						if($("#txtId").val()!=""){
							showAlertPopup({
								title: "Exluir",
								msg: "Tem Certeza que deseja excluir esse Item?",
								buttons:{
									"Sim": function(){
										utils.ajax("recibo/excluir", {id: $("#txtId").val()}, function(xml){
											var json = $.xml2json(xml);
											var msg = json.error;
											if(json.error != "0"){
												msg = "Item excluido";
												
												$("#btnSelecionaCadastrado").button("option", "disabled", true);

												$("#AdicionarReferencia").button("option", "disabled", true);
		
												$("#txtObservacao").attr("readonly", "readonly");
												$("#txtObservacao").val("");
												$("#txtId").val("");
												$("#txtDataPagamento").val("");
		
												utils.limparTabela(".table_consulta");
												closeAlertPopup();
												
											}
										});

									},
									"Nao": closeAlertPopup
	
								}

							});

						}
					});								

					$("#btnFechar").click(function(e){

						var total = parseFloat($('#txtTotalRef').val());
						var dinheiro = parseFloat($('#txtDinheiroRef').val());
						var cheque= parseFloat($('#txtChequeRef').val());
						var cartao= parseFloat($('#txtCartaoRef').val());

						

						var somaPgto = cartao + cheque + dinheiro;

						if(total != somaPgto){
							alert("Atencao!<br />Soma das formas de pagamento difere do total da conta!");
						}else{
							utils.ajax('recibo/salvar', {
								id: $('#txtId').val(),
								terreno:$('#selTerreno').val(),
								valor:$('#txtValorRef').val(),
								acrescimo:$('#txtAcrescimoRef').val(),
								dinheiro:$('#txtDinheiroRef').val(),
								cartao:$('#txtCartaoRef').val(),
								cheque:$('#txtChequeRef').val(),
								total:$('#txtTotalRef').val()
								
									
							}, function(xml){
								var json = $.xml2json(xml);

								if(json.erro=='0'){
									alert('Recibo Salvo Com sucesso');
									parent.$("body").trigger(funcaoRetorno);
									
								}else{
									alert(json.msg);

								}

								
								
							});
							
						}

						


						
						
							
					});
					
					$("#btnIniciar").click(function(e){
							if($("#txtId").val()==""){
								utils.ajax("recibo/gerarNovo", {}, function(xml){
									var json = $.xml2json(xml);

									if(json.error == "0"){
										$("#btnSelecionaCadastrado").button("option", "disabled", false);
										$("#btnExcluir").button("option", "disabled", false);
										$("#AdicionarReferencia").button("option", "disabled", false);
//										$("#txtObservacao").attr("readonly", "");
										$("#txtId").val(json.idGerado);
										$("#txtDataPagamento").val(json.dataAbertura);
										
									}
								});
							}	
					});
				</script>
			</div>
	</div>
	
	
	
	
<?php 
if(!$popup)
	include_once '../templates/footer.php';
?>